const evaluation = require("../../models/good/evaluation");
class EvaluationService {
    static async getEvaluationList({ pageNum = 1, pageSize = 10 }, data) {
        try {
            const query = {
                ...(data?.userId && { userId: data.userId }),
            };
            const skip = (pageNum - 1) * pageSize;
            const limit = parseInt(pageSize);
            
            // 获取总数
            const total = await evaluation.countDocuments(query);
            
            // 获取评价列表
            const evaluationList = await evaluation.find(query)
                .skip(skip)
                .limit(limit)
                .populate({
                    path: "userId",
                    select: "-password -__v",
                })
                .populate({
                    path: "evaluations.basetags",
                })
                .populate({
                    path: "evaluations.ratingtags",
                })
                .populate({
                    path: "evaluations.goodId",
                    populate: [
                        { path: "categoryId" },
                        { path: "tagId" }
                    ]
                })
                .lean();
                
            return {
                total,
                page: parseInt(pageNum),
                totalPages: Math.ceil(total / limit),
                list: evaluationList
            };
        } catch (error) {
            throw new Error('获取评价列表失败: ' + error.message);
        }
    }

    static async getEvaluationById(evaluationId) {
        return await evaluation.findById(evaluationId)
            .populate({
                path: "userId",
                select: "-password -__v",

                // 只选择用户名和头像
            })
            .populate({
                path: "evaluations.basetags",
                // 只选择用户名和头像
            })
            .populate({
                path: "evaluations.ratingtags",
                // 只选择用户名和头像
            })
            .populate({
                path: "evaluations.goodId",
                populate: [
                    { path: "categoryId" },
                    { path: "tagId" }
                ]
            }).lean()

    }

    static async createEvaluation(evaluationData, userId) {

        return await evaluation.create({ evaluations: evaluationData, userId });
    }

    static async updateEvaluation(evaluationId, evaluationData, userId) {
        return await evaluation.findOneAndUpdate({ _id: evaluationId, userId }, { $set: { evaluations: evaluationData } }, { new: true });
      
    }

    static async deleteEvaluation(evaluationId, userId) {
        // 确保用户只能删除自己的评价
        return await evaluation.findOneAndDelete({ _id: evaluationId, userId: userId });
    }
}
module.exports = EvaluationService;